import { Service } from 'egg';
import { v4 as uuidv4 } from 'uuid';
import Dysmsapi20170525, * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525';
import * as $OpenApi from '@alicloud/openapi-client';

import randomCode from '../util/code';

const { ACCESS_KEY_ID, ACCESS_KEY_SECRET } = process.env;

class SMSVerificationService extends Service {
  /**
   * 发送短信验证码
   * @param tel 用户电话
   * @return { sendMessageStatus: number } 短信发送结果
   */
  async findExistTel(
    tel: string,
  ) {
    const { ctx } = this;
    const exist = await ctx
      .model
      .SmsVerification
      .findOne({ where: { tel } });

    let randomCodeString = '';

    if (exist) {
      const { updatedAt } = exist;

      if (updatedAt) {
        const currentTime = new Date().getTime();
        const diffTime = currentTime - updatedAt.getTime();

        if (diffTime < 1000 * 60) {
          return { sendMessageStatus: 0 };
        }
        randomCodeString = randomCode(); // 更新验证码

        // 将生成的验证码存入数据库
        await ctx
          .model
          .SmsVerification
          .update({
            verticationCode: randomCodeString,
          }, { where: { tel } });
      }
    } else {
      randomCodeString = randomCode(); // 生成验证码
      // console.log('生成的验证码：', randomCodeString);
      // 用生成的验证码更新数据库
      await ctx
        .model
        .SmsVerification
        .create({
          verticationCode: randomCodeString,
          tel,
        });
    }
    // 发送短信
    const config = new $OpenApi.Config({
      // 您的AccessKey ID
      accessKeyId: ACCESS_KEY_ID ?? '',
      // 您的AccessKey Secret
      accessKeySecret: ACCESS_KEY_SECRET ?? '',
    });
    // 访问的域名
    config.endpoint = 'dysmsapi.aliyuncs.com';
    const client = new Dysmsapi20170525(config);

    const sendSmsRequest = new $Dysmsapi20170525.SendSmsRequest({
      phoneNumbers: tel,
      signName: '德合心理',
      templateCode: 'SMS_227737919',
      templateParam: `{"code":"${randomCodeString}"}`,
    });

    const { body } = await client.sendSms(sendSmsRequest);

    if (body.message === 'OK') {
      return { sendMessageStatus: 1 };
    }

    return { sendMessageStatus: 0 };
  }

  async create(code: string, tel: string) {
    const newCodeValidate = await this.ctx.model.SmsVerification.create({
      tel,
      verticationCode: code
    });
    return newCodeValidate;
  }

  async update(code: string, tel: string) {
    const updateCode = await this.ctx.model.SmsVerification.update({
      code
    }, { where: { tel } });

    return updateCode;
  }

  async verify(tel: string, code: string) {
    const { SmsVerification, User } = this.ctx.model;

    const result = await this.ctx.model.transaction(async (t) => {
      const foundSmsVerifications = await SmsVerification.findOne({
        where: {
          tel,
          verticationCode: code
        }
      }, { transaction: t });

      if (!foundSmsVerifications) {
        return false;
      }

      // 先查询，后插入
      const existUserData = await User.findOne({
        where: { tel }
      }, { transaction: t });

      if (!existUserData) {
        await User.create({
          uuid: uuidv4(),
          tel,
          complateFlag: 0,
        }, { transaction: t });
      }

      return true;
    });

    return result;
  }
}

module.exports = SMSVerificationService;
